package service

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/dao"
	"order_srv/handler/models"
	"strconv"
	"time"
)

// CreateOrder 创建订单
func (s *Server) CreateOrder(ctx context.Context, req *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	// 创建订单模型
	order := &models.Order{
		OrderType:      int8(req.OrderType),
		TenantID:       req.TenantId,
		LandlordID:     req.LandlordId,
		PropertyID:     req.PropertyId,
		AgentID:        req.AgentId,
		OrderStatus:    0, // 待确认
		PaymentStatus:  0, // 待支付
		LeaseStartDate: parseDate(req.LeaseStartDate),
		LeaseEndDate:   parseDate(req.LeaseEndDate),
		Remark:         req.Remark,
	}

	// 计算总金额并创建订单明细
	totalAmount := 0.0
	for _, item := range req.Items {
		// 计算金额
		amount := item.UnitPrice * item.Quantity
		totalAmount += amount

		// 创建订单明细
		orderItem := &models.OrderItem{
			ItemType:         int8(item.ItemType),
			ItemName:         item.ItemName,
			ItemDesc:         item.ItemDesc,
			UnitPrice:        item.UnitPrice,
			Quantity:         item.Quantity,
			Amount:           amount,
			BillingCycle:     int8(item.BillingCycle),
			BillingStartDate: parseDate(item.BillingStartDate),
			BillingEndDate:   parseDate(item.BillingEndDate),
		}
		order.Items = append(order.Items, orderItem)
	}
	order.TotalAmount = totalAmount

	// 调用dao层创建订单
	err := dao.CreateOrder(ctx, order)
	if err != nil {
		return &__.CreateOrderResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.CreateOrderResp{
		Code:    200,
		Message: "订单创建成功",
		OrderId: order.ID,
		OrderNo: order.OrderNo,
	}, nil
}

// GetOrder 获取订单详情
func (s *Server) GetOrder(ctx context.Context, req *__.GetOrderReq) (*__.GetOrderResp, error) {
	order, err := dao.GetOrderByID(ctx, req.OrderId)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &__.GetOrderResp{
				Code:    404,
				Message: "订单不存在",
			}, nil
		}
		return &__.GetOrderResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	// 转换订单信息
	orderInfo := convertOrderToProto(order)

	return &__.GetOrderResp{
		Code:    200,
		Message: "获取订单成功",
		Order:   orderInfo,
	}, nil
}

// GetOrdersByTenant 获取租客订单列表
func (s *Server) GetOrdersByTenant(ctx context.Context, req *__.GetOrdersByTenantReq) (*__.GetOrdersByTenantResp, error) {
	orders, total, err := dao.GetOrdersByTenantID(ctx, req.TenantId, int(req.Page), int(req.PageSize))
	if err != nil {
		return &__.GetOrdersByTenantResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	// 转换订单列表
	var orderList []*__.OrderInfo
	for _, order := range orders {
		orderList = append(orderList, convertOrderToProto(order))
	}

	return &__.GetOrdersByTenantResp{
		Code:     200,
		Message:  "获取订单列表成功",
		Orders:   orderList,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}

// GetOrdersByLandlord 获取房东订单列表
func (s *Server) GetOrdersByLandlord(ctx context.Context, req *__.GetOrdersByLandlordReq) (*__.GetOrdersByLandlordResp, error) {
	orders, total, err := dao.GetOrdersByLandlordID(ctx, req.LandlordId, int(req.Page), int(req.PageSize))
	if err != nil {
		return &__.GetOrdersByLandlordResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	// 转换订单列表
	var orderList []*__.OrderInfo
	for _, order := range orders {
		orderList = append(orderList, convertOrderToProto(order))
	}

	return &__.GetOrdersByLandlordResp{
		Code:     200,
		Message:  "获取订单列表成功",
		Orders:   orderList,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}

// UpdateOrderStatus 更新订单状态
func (s *Server) UpdateOrderStatus(ctx context.Context, req *__.UpdateOrderStatusReq) (*__.UpdateOrderStatusResp, error) {
	err := dao.UpdateOrderStatus(ctx, req.OrderId, int8(req.Status), req.OperatorId, req.OperatorType, req.Reason)
	if err != nil {
		return &__.UpdateOrderStatusResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.UpdateOrderStatusResp{
		Code:    200,
		Message: "订单状态更新成功",
	}, nil
}

// CreatePayment 创建支付记录
func (s *Server) CreatePayment(ctx context.Context, req *__.CreatePaymentReq) (*__.CreatePaymentResp, error) {
	// 创建支付记录
	payment := &models.OrderPayment{
		OrderID:        req.OrderId,
		PaymentType:    int8(req.PaymentType),
		PaymentMethod:  int8(req.PaymentMethod),
		PaymentChannel: int8(req.PaymentChannel),
		Amount:         req.Amount,
		PaymentStatus:  0, // 待支付
		Remark:         req.Remark,
	}

	err := dao.CreateOrderPayment(ctx, payment)
	if err != nil {
		return &__.CreatePaymentResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.CreatePaymentResp{
		Code:      200,
		Message:   "支付记录创建成功",
		PaymentId: payment.ID,
		PaymentNo: payment.PaymentNo,
	}, nil
}

// ProcessPayment 处理支付
func (s *Server) ProcessPayment(ctx context.Context, req *__.ProcessPaymentReq) (*__.ProcessPaymentResp, error) {
	err := dao.UpdatePaymentStatus(ctx, req.PaymentId, int8(req.Status), req.TransactionId, "")
	if err != nil {
		return &__.ProcessPaymentResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.ProcessPaymentResp{
		Code:    200,
		Message: "支付处理成功",
	}, nil
}

// CreateContract 创建合同
func (s *Server) CreateContract(ctx context.Context, req *__.CreateContractReq) (*__.CreateContractResp, error) {
	// 创建合同
	contract := &models.OrderContract{
		OrderID:           req.OrderId,
		ContractType:      int8(req.ContractType),
		ContractStatus:    1, // 待签署
		ContractContent:   req.ContractContent,
		AutoRenewal:       0,
		RenewalNoticeDays: 30,
	}

	err := dao.CreateOrderContract(ctx, contract)
	if err != nil {
		return &__.CreateContractResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.CreateContractResp{
		Code:       200,
		Message:    "合同创建成功",
		ContractId: contract.ID,
		ContractNo: contract.ContractNo,
	}, nil
}

// SignContract 签署合同
func (s *Server) SignContract(ctx context.Context, req *__.SignContractReq) (*__.SignContractResp, error) {
	err := dao.SignContract(ctx, req.ContractId, req.SignerId, req.Signature, int8(req.SignerType))
	if err != nil {
		return &__.SignContractResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.SignContractResp{
		Code:    200,
		Message: "合同签署成功",
	}, nil
}

// CreateReview 创建评价
func (s *Server) CreateReview(ctx context.Context, req *__.CreateReviewReq) (*__.CreateReviewResp, error) {
	// 创建评价
	review := &models.OrderReview{
		OrderID:             req.OrderId,
		ReviewerID:          req.ReviewerId,
		RevieweeID:          req.RevieweeId,
		ReviewType:          int8(req.ReviewType),
		OverallRating:       int8(req.OverallRating),
		ServiceRating:       int8(req.ServiceRating),
		CommunicationRating: int8(req.CommunicationRating),
		CleanlinessRating:   int8(req.CleanlinessRating),
		ValueRating:         int8(req.ValueRating),
		Content:             req.Content,
		Images:              "[]", // 默认空数组JSON
		IsAnonymous:         0,
		Status:              1, // 显示
	}

	err := dao.CreateOrderReview(ctx, review)
	if err != nil {
		return &__.CreateReviewResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.CreateReviewResp{
		Code:     200,
		Message:  "评价创建成功",
		ReviewId: review.ID,
	}, nil
}

// CreateComplaint 创建投诉
func (s *Server) CreateComplaint(ctx context.Context, req *__.CreateComplaintReq) (*__.CreateComplaintResp, error) {
	// 创建投诉
	complaint := &models.OrderComplaint{
		OrderID:        req.OrderId,
		ComplainantID:  req.ComplainantId,
		RespondentID:   req.RespondentId,
		ComplaintType:  int8(req.ComplaintType),
		ComplaintLevel: 1, // 一般
		Title:          req.Title,
		Content:        req.Content,
		Evidence:       "[]", // 默认空数组JSON
		Status:         0,    // 待处理
		Priority:       1,    // 低
	}

	err := dao.CreateOrderComplaint(ctx, complaint)
	if err != nil {
		return &__.CreateComplaintResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.CreateComplaintResp{
		Code:        200,
		Message:     "投诉创建成功",
		ComplaintId: complaint.ID,
		ComplaintNo: complaint.ComplaintNo,
	}, nil
}

// DeleteOrder 删除订单
func (s *Server) DeleteOrder(ctx context.Context, req *__.DeleteOrderReq) (*__.DeleteOrderResp, error) {
	err := dao.DeleteOrder(ctx, req.OrderId)
	if err != nil {
		return &__.DeleteOrderResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.DeleteOrderResp{
		Code:    200,
		Message: "订单删除成功",
	}, nil
}

// GetOrderStatistics 获取订单统计
func (s *Server) GetOrderStatistics(ctx context.Context, req *__.GetOrderStatisticsReq) (*__.GetOrderStatisticsResp, error) {
	// 解析日期
	var startDate, endDate time.Time
	var err error

	if req.StartDate != "" {
		startDate, err = time.Parse("2006-01-02", req.StartDate)
		if err != nil {
			return &__.GetOrderStatisticsResp{
				Code:    400,
				Message: "开始日期格式错误",
			}, nil
		}
	}

	if req.EndDate != "" {
		endDate, err = time.Parse("2006-01-02", req.EndDate)
		if err != nil {
			return &__.GetOrderStatisticsResp{
				Code:    400,
				Message: "结束日期格式错误",
			}, nil
		}
	}

	stats, err := dao.GetOrderStatistics(ctx, req.TenantId, req.LandlordId, startDate, endDate)
	if err != nil {
		return &__.GetOrderStatisticsResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	return &__.GetOrderStatisticsResp{
		Code:    200,
		Message: "获取统计信息成功",
		Stats:   convertStatsToProto(stats),
	}, nil
}

// 辅助方法

// convertOrderToProto 转换订单模型为proto格式
func convertOrderToProto(order *models.Order) *__.OrderInfo {
	orderInfo := &__.OrderInfo{
		Id:             order.ID,
		OrderNo:        order.OrderNo,
		OrderType:      int32(order.OrderType),
		TenantId:       order.TenantID,
		LandlordId:     order.LandlordID,
		PropertyId:     order.PropertyID,
		AgentId:        order.AgentID,
		OrderStatus:    int32(order.OrderStatus),
		PaymentStatus:  int32(order.PaymentStatus),
		TotalAmount:    order.TotalAmount,
		PaidAmount:     order.PaidAmount,
		RefundAmount:   order.RefundAmount,
		LeaseStartDate: order.LeaseStartDate.Format("2006-01-02"),
		LeaseEndDate:   order.LeaseEndDate.Format("2006-01-02"),
		ContractStatus: int32(order.ContractStatus),
		ContractUrl:    order.ContractURL,
		Remark:         order.Remark,
		CreatedAt:      order.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:      order.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	// 处理可选日期字段
	if order.ActualStartDate != nil {
		orderInfo.ActualStartDate = order.ActualStartDate.Format("2006-01-02")
	}
	if order.ActualEndDate != nil {
		orderInfo.ActualEndDate = order.ActualEndDate.Format("2006-01-02")
	}
	if order.ContractSignedAt != nil {
		orderInfo.ContractSignedAt = order.ContractSignedAt.Format("2006-01-02 15:04:05")
	}
	if order.CancelTime != nil {
		orderInfo.CancelTime = order.CancelTime.Format("2006-01-02 15:04:05")
	}
	if order.CancelReason != "" {
		orderInfo.CancelReason = order.CancelReason
	}

	return orderInfo
}

// convertStatsToProto 转换统计信息为proto格式
func convertStatsToProto(stats map[string]interface{}) map[string]string {
	result := make(map[string]string)
	for k, v := range stats {
		switch val := v.(type) {
		case int64:
			result[k] = strconv.FormatInt(val, 10)
		case float64:
			result[k] = strconv.FormatFloat(val, 'f', 2, 64)
		case string:
			result[k] = val
		default:
			result[k] = fmt.Sprintf("%v", val)
		}
	}
	return result
}

// parseDate 解析日期字符串
func parseDate(dateStr string) time.Time {
	if dateStr == "" {
		return time.Time{}
	}
	t, err := time.Parse("2006-01-02", dateStr)
	if err != nil {
		return time.Time{}
	}
	return t
}
